<?php
/**
 * Created by PhpStorm.
 * User: 钊鑫
 * Date: 2019/1/26
 * Time: 14:16
 */
namespace app\api\controller;

use app\api\service\Token as TokenService;
use app\api\model\Homeuser as HomeuserModel;
use app\api\validate\Homeuser as HomeuserValidate;
use \think\Image as Image;

class MyUser extends Base
{
    //获取我的信息
    public function gain(){
        $uid = TokenService::getCurrentUid();
        $result = HomeuserModel::where(['id'=>$uid])->find();
        return $this->successMessage($result);
    }

    //更改我的信息
    public function handle(){
        $uid = TokenService::getCurrentUid();//接收token，获取uid
        $validate = new HomeuserValidate($uid);
        $scene = (input('post.type') == '2') ? 'student' : 'teacher';//自定义场景
        $validate->scene($scene)->goCheck();
        $post = input('post.');

        if($this->request->file('file')){
            $file = $this->request->file('file');
        }else{
            $this->errorMessage('请选择需要上传的图片！');
        }
        $info = $file->validate(['ext'=>'jpg,png'])->rule('date')->move('./uploads/wechat/');
        if($info) {
            //写入到附件表
            $post['id'] = $uid;
            $post['image'] = 'uploads/wechat/'. $info->getSaveName();//文件路径
            $img_small = Image::open('./'.$post['image']);
            $temp = explode('/',$info->getSaveName());
            $thumb = $temp['0'].'/thumb_'.$temp['1'];
            $img_small->thumb(300,180,Image::THUMB_SCALING)->save('./uploads/wechat/'.$thumb);
            $post['image_thumb'] = 'uploads/wechat/'.$thumb;
            $post['params']['student_id'] = $post['student_id'];
            unset($post['img']);
            $result = HomeuserModel::update($post);
            if($result) {
                return $this->successMessage('更改信息成功！');
            }else {
                $this->errorMessage('更改信息失败！');
            }
        } else {
            // 上传失败获取错误信息
            $this->errorMessage($file->getError());
        }
    }

    //获取图片信息
    public function image_info(){
        $validate = new ImageTypeValidate();
        $validate->goCheck();
        $post = $validate->getDataByRule(input('post.'));//过滤非验证器中的字段
        $uid = TokenService::getCurrentUid();//接收token，获取uid
        return ImageModel::GetInfo($uid,$post);
    }
}